package com.tpshion.cloud.websocket.service;

import com.tpshion.cloud.common.support.AuthInfo;
import com.tpshion.cloud.common.utils.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Service
@ServerEndpoint("/ws/{token}")
public class WebSocketService {

    private static final Logger log = LoggerFactory.getLogger(WebSocketService.class);

    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static AtomicInteger onlineNum = new AtomicInteger();

    //concurrent包的线程安全Set，用来存放每个客户端对应的WebSocketServer对象。
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    //发送消息
    public void sendMessage(Session session, String message) throws IOException {
        if(session != null){
            synchronized (session) {
                session.getBasicRemote().sendText(message);
                log.info("sendMessage:{}",message);
            }
        }
    }

    //给指定用户发送信息
    public void sendInfo(String userId, String message){
        Session session = sessionPools.get(userId);
        try {
            sendMessage(session, message);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //建立连接成功调用
    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) throws Exception{
        if(StringUtils.isEmpty(token)){
            sendMessage(session,"没有权限");
        }
        try {
            AuthInfo userInfo = JwtUtil.getUserInfo(token);
            sessionPools.put(userInfo.getUserId(),session);
            addOnlineCount();
            log.info("{} 加入连接，连接数：{}",userInfo.getUserId(),onlineNum);
        }catch (Exception e){
            sendMessage(session,"权限验证失败");
        }
    }

    //关闭连接时调用
    @OnClose
    public void onClose(@PathParam("token") String token){
        AuthInfo userInfo = JwtUtil.getUserInfo(token);
        sessionPools.remove(userInfo.getUserId());
        log.info("{}：断开连接,连接数：{}",userInfo.getUserId(),onlineNum);
    }

    //收到客户端信息
    @OnMessage
    public void onMessage(String message) throws IOException{
        message = "客户端：" + message + ",已收到";
        System.out.println(message);
        for (Session session: sessionPools.values()) {
            try {
                sendMessage(session, message);
            } catch(Exception e){
                e.printStackTrace();
                continue;
            }
        }
    }

    //错误时调用
    @OnError
    public void onError(Session session, Throwable throwable){
        log.error("websocket error:{}",throwable.getMessage(),throwable);
    }

    public static void addOnlineCount(){
        onlineNum.incrementAndGet();
    }

    public static void subOnlineCount() {
        onlineNum.decrementAndGet();
    }
}
